#include "CameraPlayer.h"

CameraPlayer::CameraPlayer(QWidget* parent)
    : QObject(parent)
{
    m_player = new QMediaPlayer(this);
    m_vw = new QVideoWidget(parent);
    m_player->setVideoOutput(m_vw);
    connect(m_player, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),
        [=](QMediaPlayer::Error error) {
            qDebug() << "Error: " << error;
        });
    connect(m_player, &QMediaPlayer::mediaStatusChanged, this, [=](QMediaPlayer::MediaStatus st) {
        qDebug() << st;
    });
}

bool CameraPlayer::isOpened()
{
    return m_player->state() == QMediaPlayer::State::PlayingState;
}

void CameraPlayer::open(QString dev)
{
    QString pipline(
        "gst-pipeline: v4l2src device=%1 ! "
        "video/x-raw, width=640, height=480, framerate=30/1 ! "
        "videoconvert ! "
        "videoflip name=videoFlip method=none ! "
        "autovideosink name=qtvideosink");

    pipline = pipline.arg(dev);

    // pipline = "gst-pipeline: videotestsrc ! glimagesink name=qtvideosink";
    m_player->setMedia(QUrl(pipline));

    m_player->play();
    m_vw->resize(640, 480);
    m_vw->show();
    m_dev = dev;
}

void CameraPlayer::close()
{
    if (m_player) {
        m_player->stop();
    }
}

void CameraPlayer::mirred()
{
    if (m_mirr) {
        QString pipline(
            "gst-pipeline: v4l2src device=%1 ! "
            "video/x-raw, width=640, height=480, framerate=30/1 ! "
            "videoconvert ! "
            "videoflip name=videoFlip method=4 ! "
            "autovideosink name=qtvideosink");

        pipline = pipline.arg(m_dev);

        // pipline = "gst-pipeline: videotestsrc ! glimagesink name=qtvideosink";
        m_player->setMedia(QUrl(pipline));

        m_player->play();

    } else {
        QString pipline(
            "gst-pipeline: v4l2src device=%1 ! "
            "video/x-raw, width=640, height=480, framerate=30/1 ! "
            "videoconvert ! "
            "videoflip name=videoFlip method=0 ! "
            "autovideosink name=qtvideosink");

        pipline = pipline.arg(m_dev);

        // pipline = "gst-pipeline: videotestsrc ! glimagesink name=qtvideosink";
        m_player->setMedia(QUrl(pipline));

        m_player->play();
    }
    m_mirr = !m_mirr;
}
